<?php
namespace App\Http\Controllers;

use App\Models\User;
use Request, Config, Session, Validator, Hash, Res;
class AdminController extends PublicController {
    
    public function _initialize(){
    }
    public function anyLogin(){
        if (!empty(Session::get('admin.id'))) {
            return redirect('index/index');
        }
        if (!Request::has('password')) {
            return view('admin.login');
        }
        $validator = Validator::make(Request::all(), array(
                    'mobile' => 'required|digits:11',
                    'password' => 'required|min:6',
        ));
        if ($validator->fails()) {
            return view('admin.login')->withErrors($validator->errors());
        }
        $user = User::leftJoin('admin_group_member', 'users.id', '=', 'admin_group_member.user_id')
                ->where('mobile', Request::get('mobile'))
                ->select('users.*','admin_group_member.*', 'admin_group_member.user_id as admin_user_id')
                ->first();
        if (!$user) {
            return view('admin.login')->withErrors(['error' => '用户名或密码错误！']);
        }
//        exit;
        //验证密码
        if (!$this->checkPassword(Request::get('password'), $user->password)) {
            return view('admin.login')->withErrors(['error' => '密码错误！']);
        }
        //验证是否被禁用
        if ($user->status == 0) {
            return view('admin.login')->withErrors(['error' => trans('errors.User_Status_Error')]);
        }

        if($user->adminid == 1){
            Session::put('admin.id', $user->id);
            Session::put('admin.isfounder', '1');
            return redirect('index/index');
        }
        if(empty($user->admin_user_id)){
            return view('admin.login')->withErrors(['error' => '用户名或密码错误！']);
        }
        Session::put('admin.id', $user->id);
        Session::put('admin.isfounder', '');
        return redirect('index/index');
    }
    
    public function anyLogout() {
        Session::forget('admin');
        return redirect('login/login');
    }

    protected function checkPassword($password, $hashed_password){
        return Hash::check($password, $hashed_password);
    }

}
